package cn.xiqi.cms.hibernate.service;

import java.util.HashMap;
import java.util.Map;

import cn.xiqi.cms.hibernate.DAO.AccountDAO;
import cn.xiqi.cms.hibernate.beans.Accountinfo;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class AccountServiceImpl implements AccountService{
	private AccountDAO dao;

	@Override
	public int register(Accountinfo record) {
		int id = 0;
		
		id = dao.insert(record);		
		return id;
	}

	@Override
	public boolean delete(Accountinfo record) {
		boolean success = false;
		
		success = dao.delete(record);		
		return success;
	}

	@Override
	public boolean changePsw(int accountID, String newpsw) {
		boolean success = false;
		Accountinfo record = null;
		
		record = getByID(accountID);
		record.setPassword(newpsw);
		success = dao.update(record);		
		return success;
	}

	@Override
	public boolean isExist(String username) {
		Accountinfo record = null;
		Map values = new HashMap<>();
		boolean isExist = false;
		
		values.put("type", "username");
		values.put("username", username);
		record = dao.select(values).get(0);
		if(record != null)
			isExist = true;
		return isExist;
	}

	@Override
	public Accountinfo getByID(int accountid){
		Accountinfo record = null;
		Map values = new HashMap<String, Object>();
		
		values.put("type", "id");
		values.put("id", accountid);
		record = dao.select(values).get(0);
		return record;
	}

	@Override
	public boolean login(String username, String password) {
		Accountinfo record = null;
		HashMap<String, Object> values = new HashMap<String, Object>();
		boolean success;
		
		values.put("type", "username");
		values.put("username", username);
		record = dao.select(values).get(0);
		if(record.getPassword().equals(password)){
			success = true;
		}else{
			success = false;
		}
		return success;
	}

	@Override
	public void setDao(AccountDAO dao) {
		this.dao = dao;
	}

	@Override
	public Accountinfo getByUsr(int userID) {
		Accountinfo record = null;
		Map values = new HashMap<String, Object>();
		
		values.put("type", "user");
		values.put("userid", userID);
		record = dao.select(values).get(0);
		return record;
	}

}
